package com.kuzufang.modules.publish;

import android.app.Activity;
import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.donkingliang.imageselector.utils.ImageSelectorUtils;
import com.donkingliang.imageselector.view.SquareImageView;
import com.kuzufang.R;
import com.kuzufang.modules.imageutil.ImageHandler;

import java.util.ArrayList;

/**
 * Created by songyuanjin on 2017/10/10.
 */

public class RoomImageAdapter extends RecyclerView.Adapter<RoomImageAdapter.ImageItemViewHolder> {
    private ArrayList<String> images = new ArrayList<>();
    private Context mContext;
    private final static int MAX_IMAGE_COUNT = 8;

    public RoomImageAdapter(Context mContext) {
        this.mContext = mContext;
    }

    public void setImages(ArrayList<String> images) {
        this.images = images;
        notifyDataSetChanged();
    }

    @Override
    public ImageItemViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(mContext).inflate(R.layout.item_publish_find_room_image, parent, false);
        return new ImageItemViewHolder(view);
    }

    @Override
    public void onBindViewHolder(ImageItemViewHolder holder, final int position) {
        if (images.size() >= MAX_IMAGE_COUNT) {
            String itemImagePath = images.get(position);
            ImageHandler.getImageLoader().load(mContext, itemImagePath, holder.imageView);
        } else {
            if (position == getItemCount() - 1) {
                ImageHandler.getImageLoader().load(mContext,R.drawable.icon_add_image , holder.imageView);
            } else {
                String itemImagePath = images.get(position);
                ImageHandler.getImageLoader().load(mContext, itemImagePath, holder.imageView);
            }
        }

        holder.imageView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (images.size() < MAX_IMAGE_COUNT && position == getItemCount() - 1) {
                    //限数量的多选
                    ImageSelectorUtils.openPhoto((Activity) mContext, PublishFindRoommateActivity.REQUEST_CODE, false, 8, images);
                }
            }
        });

    }


    @Override
    public int getItemCount() {
        return images.size() < MAX_IMAGE_COUNT ? images.size() + 1 : images.size();
    }

    static class ImageItemViewHolder extends RecyclerView.ViewHolder {
        private SquareImageView imageView;

        public ImageItemViewHolder(View itemView) {
            super(itemView);
            this.imageView = (SquareImageView) itemView.findViewById(R.id.iv_image);
        }
    }
}
